package com.jin.webvideo.js;

import org.graalvm.polyglot.Source;

import javax.script.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SourceManager {

    public interface SourceLoader{
        String load(String name) throws IOException;
    }

    private Map<String, Source> sourceMap = new HashMap<>();
    private SourceLoader sourceLoader;
    private String scriptMimeType;

    public SourceManager(String scriptMimeType, SourceLoader sourceLoader){
        this.scriptMimeType = scriptMimeType;
        setSourceLoader(sourceLoader);
    }
    public SourceManager(String scriptMimeType){
        this.scriptMimeType = scriptMimeType;
    }
    public void setSourceLoader(SourceLoader sourceLoader) {
        this.sourceLoader = sourceLoader;
    }

    public boolean loadSource(String source, String name){
        Source src = sourceMap.get(name);

        if (null == src){
            src = Source.newBuilder(scriptMimeType, source, name).buildLiteral();
            sourceMap.put(name, src);
        }
        return true;
    }
    public Source source(String name) throws ScriptException, IOException {
        Source src = sourceMap.get(name);
        if (null == src){
            String content = null;
            try{
                content =  sourceLoader.load(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (content == null){
                throw new ScriptException(String.format("The script[name=%s] could not be found", name));
            }
            src = Source.newBuilder(scriptMimeType, content, name).build();
            sourceMap.put(name, src);
        }
        return src;
    }
    public void clear(){
        sourceMap.clear();
    }

    public String getScriptMimeType() {
        return scriptMimeType;
    }
}
